package com.jsaas.core.security;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jsaas.model.Permission;
import com.jsaas.model.User;
import com.jsaas.sys.service.PermissionService;
import com.jsaas.sys.service.UserService;
import com.jsaas.utils.Encodes;
import com.jsaas.utils.MyUtils;

/**   
 * @Title: ShiroDbRealm.java 
 * @Package com.jsaas.core.security 
 * @Description: TODO(shiro) 
 * @author tuozq 
 * @date 2017年11月3日 下午4:37:20 
 * @version V1.0   
 */
public class ShiroDbRealm extends AuthorizingRealm {
	

	/*@Override
	public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
		// TODO Auto-generated method stub
		//自定义密码验证类  集成SimpleCredentialsMatcher 实现doCredentialsMatch方法
		super.setCredentialsMatcher(new MyCredentialsMatcher());
	}*/

	/**
	 * 登录认证
	 * 身份认证
	 *  SecurityUtils.getSubject().login(token) 时调用此方法
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// TODO Auto-generated method stub
		CaptchaUsernamePasswordToken authcToken = (CaptchaUsernamePasswordToken) token;

		if (authcToken.getUsername()==null||StrKit.isBlank(authcToken.getUsername())) {
			throw new AuthenticationException("用户名不可以为空");
		}

		String account = authcToken.getUsername();
		SqlPara sqlPara = Db.getSqlPara("user.findUser", Kv.by("account", account));
		User user = User.dao.findFirst(sqlPara);
		if(MyUtils.isNotNull(user)){
			//UserPrincipal为自定义用户身份信息，登录成功后可以通过SecurityUtils.getSubject().getPrincipal()获取身份信息
			//ByteSource.Util.bytes(user.getSalt()) 订舱系统的web用户密码是salt转码之后的byte加密生成的,所以 这里传的salt需要先Encodes.decodeHex(user.getSalt())
			return new SimpleAuthenticationInfo(new UserPrincipal(user), user.getPassword(), ByteSource.Util.bytes(user.getSalt()), getName());
		}

		return null;
	}

	/**
	 * 此方法调用  hasRole,hasPermission的时候才会进行回调.
	 *
	 * 权限信息.(授权):
	 * 1、如果用户正常退出，缓存自动清空；
	 * 2、如果用户非正常退出，缓存自动清空；
	 * 3、如果我们修改了用户的权限，而用户不退出系统，修改的权限无法立即生效。
	 * :Authorization 是授权访问控制，用于对用户进行的操作授权，证明该用户是否允许进行当前操作，如访问某个链接，某个资源文件等。
	 * @param principalCollection
	 * @return
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		UserPrincipal principal = (UserPrincipal) principals.fromRealm(getName()).iterator().next();
		if (principal != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			if(principal.getAccount().equals("admin")){
				info.addStringPermissions(getAllPermission());
			}else{
				info.addStringPermissions(new UserService().findPermissionByUserId(principal.getUserId()));
			}
			return info;
		} else {
			return null;
		}
	}
	
	private List<String> getAllPermission(){
		List<String> list = new ArrayList<String>();
		Map<String, Permission> maps = PermissionService.getAllEnablePermission();
		for (String actionKey : maps.keySet()) {
			list.add(maps.get(actionKey).getPermission());
		}
		return list;
	}




}
